﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace OpSatPlan.Encoder
{
    public class HumanReadableEncoder
    {
        private CnfEncoder mEncoder;
        public HumanReadableEncoder(CnfEncoder encoder)
        {
            this.mEncoder = encoder;
        }
        public string CnfReadableFileName
        {
            get
            {
                return "cnf_readable" + System.Diagnostics.Process.GetCurrentProcess().Id.ToString() + ".txt";
            }
        }

        public void Encode()
        {
            StreamReader sr = new StreamReader(this.mEncoder.CnfFileName);
            if(File.Exists(this.CnfReadableFileName))
                File.Delete(this.CnfReadableFileName);
            StreamWriter sw = new StreamWriter(this.CnfReadableFileName);

            sr.ReadLine();
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                string rLine = "";
                string[] vars = line.Split(' ');
                foreach (string var in vars)
                {
                    try
                    {
                        int val = int.Parse(var.Trim());
                        if (val != 0)
                        {
                            int time = this.mEncoder.GetTimeStep(val);
                            AtomicFormula af = this.mEncoder.GetAtomicFormula((int)Math.Abs(val));
                            if (af != null)
                                rLine += (val > 0 ? af.ToString() : "~" + af.ToString()) + "[" + time + "] ";
                            else
                            {
                                Operator op = this.mEncoder.GetOperator((int)Math.Abs(val));
                                rLine += (val > 0 ? op.ToString() : "~" + op.ToString()) + "[" + time + "] ";
                            }
                        }
                    }
                    catch (Exception e)
                    {
                    }
                }
                sw.WriteLine(rLine);

            }
            sw.Close();
            sr.Close();
        }
    }
}
